<?php
/**
 * 商品与规格值ID的组合 关联表
 * 商品 A 关联规格 A1,B1,C1 为一个 SKU，一个 SKU 可以有对应价格 / 图片 / 库存等，
 * SKU 是商品的最小销售单元
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/6/7
 * @copyright PanxSoft Inc.
 */
namespace App\Models\Panx;

use App\Observers\BosCleanObserver;
use App\Services\Utils\Bosable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * Class ProductSku
 *
 * @property int[] spec_value_ids
 *
 * @mixin Builder
 * @package App\Models\Panx
 */
class ProductSku extends Model
{
    use Bosable;

    protected $thumb_bos_key_prefix = 'product/sku/';

    protected $table = 'product_skus';

    protected $guarded = [];
    
    protected $bos_columns = ['thumb'];
    
    protected $casts = [
        'spec_value_ids' => 'array'
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function product()
    {
        return $this->belongsTo(Product::class, 'product_id', 'id');
    }

    /**
     * @param $thumb
     * @throws \Exception
     */
    public function setThumbAttribute($thumb)
    {
        if (is_file($thumb)) {
            $this->attributes['thumb'] = $this->uploadPostFile($thumb , $this->thumb_bos_key_prefix);
        } elseif (is_string($thumb)) {
            $this->attributes['thumb'] = $thumb;
        }
    }

    /**
     * @return mixed|null
     */
    public function getThumbAttribute()
    {
        if (! $this->attributes['thumb']) return null;

        return $this->getStaticUrl($this->attributes['thumb']);
    }

    /**
     * @return mixed|null
     */
    public function getSpecValueIdsStrAttribute()
    {
        return $this->attributes['spec_value_ids'];
    }
    
    /**
     * 注册删除 bosKey 事件绑定
     */
    protected static function boot()
    {
        parent::boot();
        
        /*
         * 监听bos清理事件
         */
//        self::observe(BosCleanObserver::class);
    }
}
